<template>
  <div class="login">
    <el-form
      ref="login"
      :model="loginForm"
      :rules="rules"
      class="loginf"
      label-width="100px"
    >
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" clearable 
          >2332</el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" clearable show-password
          >233</el-input>
      </el-form-item>
      <!-- 登录按钮 -->
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// 引入辅助性函数
import {mapActions} from 'vuex'
import {userLogin} from '../util/request/api'
export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "", 
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    ...mapActions(['changeUserAction']),
    login() {
        // console.log(this.$refs.login,'ref属性');
      this.$refs.login.validate((valid) => {
        //    valid代表的是用户名和密码规格知否正确
        console.log(valid);
        if (valid) {
          userLogin(this.loginForm)
          .then(res=>{
            console.log(res); 
            if (res.code==200) {
              // res.list是一个对象不可以直接存储，要转成字符串，存进本地存储
              // sessionStorage.setItem('userinfo',JSON.stringify(res.list))
              // 传给左侧列表
              console.log(res);
              this.changeUserAction(res.list)
              // 跳转至首页
            this.$router.push("/home");
            // 提示
            this.$message.success(res.msg);
            }else {
            this.$message.error(res.msg);
          }
          })
          // 写死的数据
          // if (
          //   this.loginForm.username == "admin" &&
          //   this.loginForm.password == "123456"
          // ) {
          //   this.$router.push("/home");
          //   this.$message.success("登录成功");
          // } else{ 
          //   this.$message.error("用户名或者密码不正确");
          // }
        } else {
          // 验证失败
          console.log(valid, "err");
        }
      });
    },
  },
};
</script>
<style scoped>
.login {
  width: 100vw;
  height: 47vw;
  background-color: #ece0dd;
  display: flex;
  justify-content: center;
  align-items: center;
}
.loginf {
  width: 500px;
  height: 350px;
}
</style>